using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Common
{
    public class StreamEx : BaseStream
    {
        public virtual PropertyKey ReadKey()
        {
            return (PropertyKey)ReadInt();
        }

        public virtual void Write(PropertyKey key)
        {
            Write((int)key);
        }

        public virtual void WriteIndex(List<PropertyKey> keys, List<byte[]> dates)
        {
            int num = keys.Count * 8 + 4;
            int value = num + dates.Sum((byte[] s) => s.Length + 4);
            Write(value);
            for (int i = 0; i < keys.Count; i++)
            {
                num += ((i != 0) ? (dates[i - 1].Length + 4) : 0);
                Write(keys[i]);
                Write(num);
            }
            Write(PropertyKey.Key_End);
            for (int j = 0; j < dates.Count; j++)
            {
                Write(dates[j].Length);
                Write(dates[j]);
            }
            Flush();
        }

        public virtual void ReadIndex(out List<PropertyKey> keys, out List<byte[]> dates)
        {
            StreamEx streamEx = new StreamEx();
            int len = ReadInt();
            byte[] array = ReadBytes(len);
            streamEx.Write(array);
            streamEx.Seek(0L, SeekOrigin.Begin);
            keys = new List<PropertyKey>();
            dates = new List<byte[]>();
            PropertyKey item;
            while ((item = streamEx.ReadKey()) != PropertyKey.Key_End)
            {
                keys.Add(item);
                int num = streamEx.ReadInt();
                int num2 = (int)streamEx.Position;
                streamEx.Seek(num, SeekOrigin.Begin);
                dates.Add(streamEx.ReadBytes(streamEx.ReadInt()));
                streamEx.Seek(num2, SeekOrigin.Begin);
            }
            streamEx.Close();
        }
    }
}
